import os

import pandas as pd
from config.database import AsyncSessionLocal
from sqlalchemy import func, select
from utils.log_util import logger
from utils.pwd_util import PwdUtil

from module_admin.entity.do.config_do import SysConfig
from module_admin.entity.do.demo_do import Demo
from module_admin.entity.do.menu_do import SysMenu
from module_admin.entity.do.role_do import SysRole
from module_admin.entity.do.user_do import SysUser
from module_admin.entity.vo.config_vo import ConfigModel
from module_admin.entity.vo.demo_vo import DemoModel
from module_admin.entity.vo.menu_vo import MenuModel
from module_admin.entity.vo.role_vo import AddRoleModel
from module_admin.entity.vo.user_vo import (
    AddUserModel,
)
from module_admin.service.config_service import ConfigService
from module_admin.service.demo_service import DemoService
from module_admin.service.menu_service import MenuService
from module_admin.service.role_service import RoleService
from module_admin.service.user_service import UserService


class StartService:
    """启动服务初始化"""

    @classmethod
    async def init_datas(cls):
        """
        新增用户信息service

        :param query_db: orm对象
        :param page_object: 新增用户对象
        :return: 新增用户校验结果
        """

        async with AsyncSessionLocal() as db:
            await cls.init_config(db)
            await cls.init_role(db)
            await cls.init_user(db)
            await cls.init_menu(db)

        async with AsyncSessionLocal() as db:
            count_demo = (await db.execute(select(func.count('*')).select_from(Demo))).scalar()

            if count_demo == 0:
                logger.info('初始化Demo数据')
                add_demo = DemoModel(
                    id=1,
                    code='000000',
                    name='测试1',
                    age=18,
                    money=100.0,
                    createBy='初始化',
                )
                # logger.info(add_user)
                add_result = await DemoService.add_demo_services(db, add_demo)
                logger.info(add_result)

            add_demo = DemoModel(
                code='000001',
                name='测试',
                age=19,
                money=120.0,
            )
            add_result = await DemoService.add_demo_services(db, add_demo)
            logger.info(add_result)

    @classmethod
    async def init_config(cls, db):
        """
        读取csv文件初始化系统配置
        """
        logger.info('初始化系统配置')
        filepath = os.path.join('app/data/admin', 'sys_config.csv')
        df = pd.read_csv(filepath, encoding='utf-8')
        for _, row in df.iterrows():
            count = (
                await db.execute(
                    select(func.count('*')).select_from(SysConfig).where(SysConfig.config_key == row['config_key'])
                )
            ).scalar()

            logger.info(f'初始 {row}')
            if count == 0:
                add_config = ConfigModel(
                    configId=int(row['config_id']),
                    configName=str(row['config_name']),
                    configKey=str(row['config_key']),
                    configValue=str(row['config_value']),
                    configType=str(row['config_type']),
                    createBy='初始化',
                    remark=str(row['remark']),
                )
                await ConfigService.add_config_services(None, db, add_config)

    @classmethod
    async def init_menu(cls, db):
        """
        读取csv文件初始化系统配置
        """
        logger.info('初始化菜单')
        filepath = os.path.join('app/data/admin', 'sys_menu.csv')
        # na_filter=False 忽略空值
        df = pd.read_csv(filepath, encoding='utf-8', na_filter=False)
        for _, row in df.iterrows():
            count = (
                await db.execute(
                    select(func.count('*')).select_from(SysMenu).where(SysMenu.menu_name == row['menu_name'])
                )
            ).scalar()
            if count == 0:
                add_menu = MenuModel(
                    menuId=int(row['menu_id']),
                    menuName=str(row['menu_name']),
                    menuType=str(row['menu_type']),
                    parentId=int(row['parent_id']),
                    path=str(row['path']),
                    component=str(row['component']),
                    query=str(row['query']),
                    perms=str(row['perms']),
                    icon=str(row['icon']),
                    visible=str(row['visible']),
                    status=str(row['status']),
                    orderNum=int(row['order_num']),
                    createBy='初始化',
                    remark=str(row['remark']),
                )
                await MenuService.add_menu_services(db, add_menu)

    @classmethod
    async def init_role(cls, db):
        """
        读取csv文件初始化系统配置
        """
        logger.info('初始化角色')
        filepath = os.path.join('app/data/admin', 'sys_role.csv')
        df = pd.read_csv(filepath, encoding='utf-8')
        for _, row in df.iterrows():
            count = (
                await db.execute(
                    select(func.count('*')).select_from(SysRole).where(SysRole.role_key == row['role_key'])
                )
            ).scalar()
            if count == 0:
                add_role = AddRoleModel(
                    roleId=int(row['role_id']),
                    roleName=str(row['role_name']),
                    roleKey=str(row['role_key']),
                    roleSort=int(row['role_sort']),
                    status='0',
                    createBy='初始化',
                )
                await RoleService.add_role_services(db, add_role)

    @classmethod
    async def init_user(cls, db):
        logger.info('初始化用户')
        filepath = os.path.join('app/data/admin', 'sys_user.csv')
        df = pd.read_csv(filepath, encoding='utf-8')
        for _, row in df.iterrows():
            count = (
                await db.execute(
                    select(func.count('*')).select_from(SysUser).where(SysUser.user_name == row['user_name'])
                )
            ).scalar()
            if count == 0:
                add_user = AddUserModel(
                    userId=int(row['user_id']),
                    userName=str(row['user_name']),
                    nickName=str(row['nick_name']),
                    password=PwdUtil.get_password_hash('a123456'),
                    email=str(row['email']),
                    phonenumber=str(row['phonenumber']),
                    sex=str(row['sex']),
                    userType='00',
                    status='0',
                    # roleIds=[1],
                    roleIds=list(map(int, row['role_ids'].split('|'))),
                    # dept_id=1,
                    # createTime=datetime.now(),
                    createBy='初始化',
                )
                # logger.info(add_user)
                add_user_result = await UserService.add_user_services(db, add_user)
                logger.info(add_user_result.message)
